import { ref, onMounted, onBeforeUnmount, onUnmounted, reactive, nextTick } from 'vue'
import { showToast, closeToast, showLoadingToast } from 'vant'

import { apiConfigurable } from '@/request/api/api'

export const useEventFunc = () => {
  let jdata = null
  let itableType = 'head'
  let ibodyDataIndex = 0
  let ibodyDataName = ''

  function parseEventSource(eventSource, jsondata, tableType, bodyDataIndex, bodyDataName, clickItem) {
    jdata = jsondata
    itableType = tableType //类型:表头or表体
    ibodyDataIndex = bodyDataIndex //表体索引
    ibodyDataName = bodyDataName //表体名

    const funcArr = eventSource.split(';')
    funcArr.forEach((item, index) => {
      eval(item)
    })
  }
  const dispatchshhystj = () => {}

  function hhys(formula, AffectsFields, accuracy) {
    if (!formula || !AffectsFields || !accuracy) {
      showToast('运算函数参数不全,请检查事件函数')
    }
    const variableArr = IextractVariables(formula).map((item) => {
      return { field: item, value: IgetFiledValue(item) }
    })

    // 检查变量的值是否可以参与运算
    if (variableArr.every((item) => /^-?\d+(\.\d+)?$/.test(item.value))) {
      const expression = variableArr.reduce((pre, item, index) => {
        return pre.replace(item.field, item.value)
      }, formula)

      const targetFieldItem = IgetFiledItem(AffectsFields)

      targetFieldItem.value = eval(expression).toFixed(accuracy)
    }
  }
  //销售订单客户失去焦点事件 查配送商业带出价格
  function consumerOnblur(v) {
    const sorders = jdata.bodydata[Object.keys(jdata.bodydata)[0]]
    const params = []
    const consumer = IgetFiledItem('sorder_consumer')
    for (let i = 0; i < sorders.length; i++) {
      const fields = sorders[i]
      const obj = {
        product: '',
        tgxydh: ''
      }
      for (let j = 0; j < fields.length; j++) {
        const item = fields[j]
        if (item.sField === 'product') {
          obj.product = item.valuehidden
        }
        if (item.sField === 'tgxydh') {
          obj.tgxydh = item.valuehidden
        }
      }
      params.push(obj)
    }

    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    })
    nextTick(() => {
      apiConfigurable('sorder.checkprice.do', { pt: JSON.stringify(params), sykh: consumer.value })
        .then((res) => {
          // 表体循环
        const bodydata = jdata.bodydata
          for (const key in bodydata) {
            if (bodydata.hasOwnProperty(key)) {
              const bodyArr = bodydata[key]
              for (let i = 0; i < bodyArr.length; i++) {
                if (i == ibodyDataIndex) {
                  const group = bodyArr[i]
                  for (let j = 0; j < group.length; j++) {
                    const item = group[j]
                    if (item.sField === 'price') {
                      item.value = res.data[0]
                    }
                    if (item.sField === 'xyj') {
                      item.value = res.data[0]
                    }
                    if (item.sField === 'js') {
                      item.value = ''
                    }
                  }
                }
              }
            }
          }
        })
        .finally(() => {
          closeToast()
        })
    })

    // var sorders = document.getElementsByClassName("listline");
    // var l = sorders.length;
    // var params = new Array();
    // var consumer = document.getElementsByName("sorder_consumer")[0].value;
    // for (var i = 0; i < l; i++) {
    //     var p = document.getElementsByName(i + "_sorders_product")[0].value;
    //     var dh;
    //     if (document.getElementsByName(i + "_sorders_tgxydh")[0] != undefined) {
    //         dh = document.getElementsByName(i + "_sorders_tgxydh")[0].value;
    //     }
    //     var obj = {};
    //     var obj = {
    //         product: p,
    //         tgxydh: dh
    //     }
    //     params[i] = obj;
    // }

    // if (consumer) {
    //     $.get("sorder.checkprice.do", { pt: JSON.stringify(params), sykh: consumer }, function (data, status) {
    //         var result = JSON.parse(data);
    //         for (var i = 0; i < l; i++) {
    //             var price = result[i];
    //             console.log(price);
    //             if (price) {
    //                 var pro = document.getElementsByName(i + "_sorders_product")[0].value;
    //                 var priceElt = document.getElementsByName(i + "_sorders_price")[0];
    //                 var xyjElt = document.getElementsByName(i + "_sorders_xyj")[0];
    //                 var jsElt = document.getElementsByName(i + "_sorders_js")[0];
    //                 priceElt.value = price;
    //                 xyjElt.value = price;
    //                 jsElt.value = '';
    //             }
    //         }

    //     });
    // }
  }

  function hhysnew(express, targetObjectField, keepN, condition) {
    const idobject = condition.split('_')[0]
    const field = condition.split('_')[1]

    const fieldArr = jdata.bodydata[ibodyDataName][ibodyDataIndex] || []
    const fieldItem = fieldArr.find((item) => item.sField === field && item.idObject === idobject)
    const pid = fieldItem.valuehidden
    if (!pid) {
      return
    }

    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    })
    apiConfigurable('sorder.checkprice.do', 'pid=' + pid)
      .then((res) => {
        if (res.code === 200) {
          const shuxing = res.data?.shuxing
          if (shuxing && shuxing.indexOf('2c9a2d927337429d01733c35268002c8') >= 0) {
            hhys(express, targetObjectField, keepN)
          }
        }
      })
      .finally(() => {
        closeToast()
      })

    return
    var event_target = $(event.target)[0]
    var type = 'post'
    var number = $(event_target).parents('tr')[0].getAttribute('number') + '_'
    // var pid = $("input[name='" + number + condition + "']")[0].value;
    var shuxing = ''
    $.ajax({
      type: type,
      url: 'product.cpsx.do',
      data: 'pid=' + pid,
      async: false,
      success: function (data) {
        var obj = jQuery.parseJSON(data)
        shuxing = obj.shuxing
      }
    })
    if (shuxing.indexOf('2c9a2d927337429d01733c35268002c8') >= 0) {
      hhys(express, targetObjectField, keepN)
    }
  }

  //参照类型失去焦点(移动端无用,但是方法要保留,不然会报错)
  function refonblur() {}

  function IgetFiledValue(objectFiled) {
    const object = objectFiled.split('_')[0]
    const field = objectFiled.split('_')[1]

    if (jdata) {
      const head = jdata.head
      const bodydata = jdata.bodydata

      // 表头循环
      for (let i = 0; i < head.length; i++) {
        const groupvalue = head[i].groupvalue
        for (let j = 0; j < groupvalue.length; j++) {
          const item = groupvalue[j]
          if (item.idObject === object && item.sField === field) {
            return item.value
          }
        }
      }
      // 表体循环
      for (const key in bodydata) {
        if (bodydata.hasOwnProperty(key)) {
          const bodyArr = bodydata[key]
          for (let i = 0; i < bodyArr.length; i++) {
            if (i == ibodyDataIndex) {
              const group = bodyArr[i]
              for (let j = 0; j < group.length; j++) {
                const item = group[j]
                if (item.idObject === object && item.sField === field) {
                  return item.value
                }
              }
            }
          }
        }
      }
    }
  }
  function IgetFiledItem(objectFiled) {
    const object = objectFiled.split('_')[0]
    const field = objectFiled.split('_')[1]
    if (jdata) {
      const head = jdata.head
      const bodydata = jdata.bodydata
      let linkItem

      // 表头循环
      for (let i = 0; i < head.length; i++) {
        const groupvalue = head[i].groupvalue
        for (let j = 0; j < groupvalue.length; j++) {
          const item = groupvalue[j]
          if (item.idObject === object && item.sField === field) {
            linkItem = item
          }
        }
      }
      // 表体循环
      for (const key in bodydata) {
        if (bodydata.hasOwnProperty(key)) {
          const bodyArr = bodydata[key]
          for (let i = 0; i < bodyArr.length; i++) {
            if (i == ibodyDataIndex) {
              const group = bodyArr[i]
              for (let j = 0; j < group.length; j++) {
                const item = group[j]
                if (item.idObject === object && item.sField === field) {
                  linkItem = item
                }
              }
            }
          }
        }
      }
      console.log(linkItem, 77)
      return linkItem
    }
  }
  function IextractVariables(formula) {
    // 正则表达式匹配以字母开头，后面可以跟数字的变量
    const variableRegex = /[a-z_A-Z]\w*/g
    const variables = formula.match(variableRegex)
    return variables
  }

  return {
    parseEventSource,
    hhys,
    hhysnew,
    consumerOnblur,
    refonblur,
    dispatchshhystj
  }
}
